'use strict';
const BaseController = require('../base');
const {
  orderIdValidate,
  orderListValidate,
} = require('@validators/orders');

class OrdersController extends BaseController {
  async add() {
    const { ctx } = this;
    const v = await orderIdValidate(ctx);
    const result = await ctx.service.orders.add({
      userId: ctx.userId,
      houseId: v.get('path.id'),
      isPayed: 0,
      createTime: ctx.helper.nowTime(),
    });

    this.success(result);
  }

  async delete() {
    const { ctx } = this;
    const v = await orderIdValidate(ctx);
    const result = await ctx.service.orders.delete({
      houseId: v.get('path.id'),
    });

    this.success(result);
  }

  async lists() {
    const { ctx } = this;
    await orderListValidate(ctx);
    const result = await ctx.service.orders.lists({
      ...ctx.params(),
      userId: ctx.userId,
    });

    this.success(result);
  }

  async invokePay(params) {
    return {
      orderNumber: params.id + new Date().getTime(),
    };
  }

  async pay() {
    const { ctx } = this;
    const v = await orderIdValidate(ctx);
    const id = v.get('path.id');
    const beforePay = await this.invokePay({ id });
    const result = await ctx.service.orders.pay({
      id,
      orderNumber: beforePay.orderNumber,
    });
    this.success(result);
  }

  async detail() {
    const { ctx } = this;
    const v = await orderIdValidate(ctx);
    const result = await ctx.service.orders.hasOrder(ctx, {
      userId: ctx.userId,
      houseId: v.get('path.id'),
    });

    this.success(result);
  }
}

module.exports = OrdersController;
